<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Layout Editor</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: sans-serif;
            display: flex;
            height: 100vh;
            margin: 0;
            background-color: #333;
            color: white;
        }

        #sidebar {
            width: 200px;
            background: #444;
            padding: 10px;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }

        #sidebar img {
            width: 100%;
            cursor: grab;
        }

        #canvas-container {
            flex-grow: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 10px;
        }

        #canvas-wrapper {
            position: relative;
            width: 100%;
            max-width: calc((100vh - 40px) * 16 / 9);
            aspect-ratio: 16 / 9;
            background-color: #000;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
            overflow: hidden;
            /* Ensure video stays within bounds */
        }

        #canvas {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 2;
        }

        #background-video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            z-index: 1;
        }

        .draggable {
            position: absolute;
            width: 150px;
            height: auto;
            touch-action: none;
            user-select: none;
            border: 2px dashed transparent;
        }

        .draggable.can-resize {
            border-color: #29e;
        }

        .delete-btn {
            position: absolute;
            top: -10px;
            right: -10px;
            background: red;
            color: white;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            text-align: center;
            line-height: 20px;
            cursor: pointer;
            display: none;
        }

        .draggable:hover .delete-btn {
            display: block;
        }

        #controls {
            position: absolute;
            top: 20px;
            right: 20px;
            z-index: 100;
            display: flex;
            gap: 10px;
        }

        button {
            padding: 10px 15px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>

    <div id="sidebar">
        <h3>Assets</h3>
        <button id="add-image-btn">Add Image</button>
        <input type="file" id="image-upload" accept="image/*" style="display: none;">
        <button id="add-text-btn">添加文字</button>
        <!-- Asset images will be loaded here by JavaScript -->
    </div>

    <div id="canvas-container">
        <div id="controls">
            <button id="save-btn">Save Layout</button>
            <button id="save-preview-btn">Save Preview Only</button>
            <button id="load-btn">Load Layout</button>
        </div>
        <div id="canvas-wrapper">
            <video id="background-video" autoplay muted loop playsinline>
                <source src="../素材/背景动画.mp4" type="video/mp4">
            </video>
            <div id="canvas"></div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const canvas = document.getElementById('canvas');
            const sidebar = document.getElementById('sidebar');
            const saveBtn = document.getElementById('save-btn');
            const loadBtn = document.getElementById('load-btn');
            const addImageBtn = document.getElementById('add-image-btn');
            const imageUpload = document.getElementById('image-upload');
            const savePreviewBtn = document.getElementById('save-preview-btn');
            const addTextBtn = document.getElementById('add-text-btn');
            let elementCounter = 0;

            addImageBtn.addEventListener('click', () => imageUpload.click());

            // Add text functionality
            addTextBtn.addEventListener('click', () => {
                const text = prompt('请输入文字内容:', '首服一区');
                if (text) {
                    createTextElement(text);
                }
            });

            function createTextElement(content) {
                const textElement = document.createElement('div');
                textElement.className = 'text-element';
                textElement.textContent = content;
                textElement.style.position = 'absolute';
                textElement.style.left = '50px';
                textElement.style.top = '50px';
                textElement.style.color = 'white';
                textElement.style.fontSize = '24px';
                textElement.style.fontWeight = 'bold';
                textElement.style.cursor = 'move';
                textElement.style.userSelect = 'none';
                textElement.style.padding = '5px';
                textElement.style.border = '1px dashed rgba(255,255,255,0.3)';
                textElement.dataset.type = 'text';
                textElement.dataset.content = content;
                textElement.dataset.fontSize = '24';
                textElement.dataset.color = 'white';
                textElement.id = `text-${++elementCounter}`;

                canvas.appendChild(textElement);
                makeInteractive(textElement);

                // Add double-click to edit
                textElement.addEventListener('dblclick', () => {
                    const newContent = prompt('编辑文字:', textElement.textContent);
                    if (newContent !== null) {
                        textElement.textContent = newContent;
                        textElement.dataset.content = newContent;
                    }
                });
            }

            imageUpload.addEventListener('change', (event) => {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const src = e.target.result;
                        const img = document.createElement('img');
                        img.src = src;
                        img.alt = file.name;
                        img.dataset.src = src;
                        sidebar.appendChild(img);

                        // Make the new image draggable
                        makeSidebarImageDraggable(img);
                    };
                    reader.readAsDataURL(file);
                }
            });

            const assets = [
                'assets/main_logo.png',
                'assets/icon.png',
                'assets/server_icon.png',
                'assets/text_prompt.png',
                'assets/age_rating.png',
                'assets/qr_code.png'
            ];

            // Assets are now loaded below with draggable functionality

            function makeInteractive(element) {
                interact(element).draggable({
                    listeners: {
                        move(event) {
                            const target = event.target;
                            const x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
                            const y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
                            target.style.transform = `translate(${x}px, ${y}px)`;
                            target.setAttribute('data-x', x);
                            target.setAttribute('data-y', y);
                        }
                    },
                    inertia: true,
                    modifiers: [interact.modifiers.restrictRect({ restriction: 'parent', endOnly: true })]
                }).resizable({
                    edges: { left: true, right: true, bottom: true, top: true },
                    listeners: {
                        move(event) {
                            const target = event.target;
                            let x = (parseFloat(target.getAttribute('data-x')) || 0);
                            let y = (parseFloat(target.getAttribute('data-y')) || 0);
                            target.style.width = event.rect.width + 'px';
                            target.style.height = 'auto';
                            x += event.deltaRect.left;
                            y += event.deltaRect.top;
                            target.style.transform = `translate(${x}px, ${y}px)`;
                            target.setAttribute('data-x', x);
                            target.setAttribute('data-y', y);
                        }
                    },
                    modifiers: [interact.modifiers.restrictSize({ min: { width: 20, height: 20 } })],
                    inertia: true
                }).on('resizemove', event => {
                    event.target.classList.add('can-resize');
                }).on('resizeend', event => {
                    event.target.classList.remove('can-resize');
                });
            }

            function makeSidebarImageDraggable(img) {
                img.addEventListener('mousedown', function (e) {
                    e.preventDefault();
                    const startX = e.clientX;
                    const startY = e.clientY;
                    const imgRect = img.getBoundingClientRect();

                    // Create a clone for visual feedback
                    const clone = img.cloneNode(true);
                    clone.style.position = 'fixed';
                    clone.style.left = imgRect.left + 'px';
                    clone.style.top = imgRect.top + 'px';
                    clone.style.zIndex = '1000';
                    clone.style.pointerEvents = 'none';
                    clone.style.opacity = '0.8';
                    document.body.appendChild(clone);

                    function onMouseMove(e) {
                        const deltaX = e.clientX - startX;
                        const deltaY = e.clientY - startY;
                        clone.style.left = (imgRect.left + deltaX) + 'px';
                        clone.style.top = (imgRect.top + deltaY) + 'px';
                    }

                    function onMouseUp(e) {
                        document.removeEventListener('mousemove', onMouseMove);
                        document.removeEventListener('mouseup', onMouseUp);

                        const canvasRect = canvas.getBoundingClientRect();

                        // Check if dropped on canvas
                        if (e.clientX >= canvasRect.left && e.clientX <= canvasRect.right &&
                            e.clientY >= canvasRect.top && e.clientY <= canvasRect.bottom) {

                            const newElement = document.createElement('div');
                            newElement.classList.add('draggable');
                            const newImg = document.createElement('img');
                            newImg.src = img.dataset.src;
                            newImg.style.width = '100%';
                            newImg.style.height = 'auto';
                            newElement.appendChild(newImg);

                            const deleteBtn = document.createElement('div');
                            deleteBtn.className = 'delete-btn';
                            deleteBtn.innerHTML = '&times;';
                            deleteBtn.onclick = () => newElement.remove();
                            newElement.appendChild(deleteBtn);

                            const x = e.clientX - canvasRect.left - 75;
                            const y = e.clientY - canvasRect.top - 50;
                            newElement.style.transform = `translate(${x}px, ${y}px)`;
                            newElement.setAttribute('data-x', x);
                            newElement.setAttribute('data-y', y);
                            newElement.setAttribute('data-src', img.dataset.src);
                            newElement.id = 'element-' + (elementCounter++);

                            canvas.appendChild(newElement);
                            makeInteractive(newElement);
                        }

                        clone.remove();
                    }

                    document.addEventListener('mousemove', onMouseMove);
                    document.addEventListener('mouseup', onMouseUp);
                });
            }


            // Add support for dropping files from the desktop
            const canvasWrapper = document.getElementById('canvas-wrapper');
            canvasWrapper.addEventListener('dragover', function (e) {
                e.preventDefault(); // This is necessary to allow dropping
                e.dataTransfer.dropEffect = 'copy';
            });

            canvasWrapper.addEventListener('drop', function (e) {
                e.preventDefault();
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    const file = files[0];
                    if (file.type.startsWith('image/')) {
                        const reader = new FileReader();
                        reader.onload = function (event) {
                            const src = event.target.result;
                            const canvasRect = canvas.getBoundingClientRect();

                            const newElement = document.createElement('div');
                            newElement.classList.add('draggable');
                            const newImg = document.createElement('img');
                            newImg.src = src;
                            newImg.style.width = '100%';
                            newImg.style.height = 'auto';
                            newElement.appendChild(newImg);

                            const deleteBtn = document.createElement('div');
                            deleteBtn.className = 'delete-btn';
                            deleteBtn.innerHTML = '&times;';
                            deleteBtn.onclick = () => newElement.remove();
                            newElement.appendChild(deleteBtn);

                            const x = e.clientX - canvasRect.left - 75;
                            const y = e.clientY - canvasRect.top - 50;
                            newElement.style.transform = `translate(${x}px, ${y}px)`;
                            newElement.setAttribute('data-x', x);
                            newElement.setAttribute('data-y', y);
                            newElement.setAttribute('data-src', src);
                            newElement.id = 'element-' + (elementCounter++);

                            canvas.appendChild(newElement);
                            makeInteractive(newElement);
                        };
                        reader.readAsDataURL(file);
                    }
                }
            });

            assets.forEach(src => {
                const img = document.createElement('img');
                img.src = src;
                img.alt = src.split('/').pop().split('.')[0];
                img.dataset.src = src;
                sidebar.appendChild(img);
                makeSidebarImageDraggable(img); // Apply draggable to pre-loaded assets
            });

            saveBtn.addEventListener('click', () => {
                const layout = [];
                document.querySelectorAll('.draggable, .text-element').forEach(el => {
                    const isText = el.classList.contains('text-element');
                    const elementData = {
                        id: el.id,
                        x: parseFloat(el.dataset.x) || 0,
                        y: parseFloat(el.dataset.y) || 0,
                        transform: el.style.transform,
                        type: isText ? 'text' : 'image'
                    };

                    if (isText) {
                        elementData.content = el.dataset.content || el.textContent;
                        elementData.fontSize = el.dataset.fontSize || '24';
                        elementData.color = el.dataset.color || 'white';
                    } else {
                        elementData.src = el.dataset.src;
                        elementData.width = el.style.width || '150px';
                    }
                    layout.push(elementData);
                });

                // 保存 layout.json
                const jsonBlob = new Blob([JSON.stringify(layout, null, 2)], { type: 'application/json' });
                const jsonLink = document.createElement('a');
                jsonLink.href = URL.createObjectURL(jsonBlob);
                jsonLink.download = 'layout.json';
                jsonLink.click();
                URL.revokeObjectURL(jsonLink.href);

                // 生成预览HTML
                const previewHtml = generatePreviewHtml(layout);
                const htmlBlob = new Blob([previewHtml], { type: 'text/html' });
                const htmlLink = document.createElement('a');
                htmlLink.href = URL.createObjectURL(htmlBlob);
                htmlLink.download = 'layout_preview.html';
                htmlLink.click();
                URL.revokeObjectURL(htmlLink.href);

                alert('已保存 layout.json 和 layout_preview.html 文件！');
            });

            // 新增：仅保存预览窗格内容
            savePreviewBtn.addEventListener('click', () => {
                const previewLayout = [];

                // 直接从画布中获取当前所有元素的最终状态
                document.querySelectorAll('#canvas .draggable, #canvas .text-element').forEach(el => {
                    const isText = el.classList.contains('text-element');
                    const rect = el.getBoundingClientRect();
                    const canvasRect = canvas.getBoundingClientRect();

                    // 计算相对于画布的位置
                    const relativeX = rect.left - canvasRect.left;
                    const relativeY = rect.top - canvasRect.top;

                    const elementData = {
                        id: el.id,
                        x: relativeX,
                        y: relativeY,
                        type: isText ? 'text' : 'image'
                    };

                    if (isText) {
                        elementData.content = el.textContent;
                        elementData.fontSize = parseInt(window.getComputedStyle(el).fontSize) || 24;
                        elementData.color = window.getComputedStyle(el).color || 'white';
                        elementData.fontWeight = window.getComputedStyle(el).fontWeight || 'bold';
                    } else {
                        const img = el.querySelector('img');
                        if (img) {
                            elementData.src = img.src;
                            elementData.width = rect.width;
                            elementData.height = rect.height;
                        }
                    }
                    previewLayout.push(elementData);
                });

                // 生成纯净的预览HTML（不包含编辑功能）
                const cleanPreviewHtml = generateCleanPreviewHtml(previewLayout);

                // 保存预览布局JSON
                const jsonBlob = new Blob([JSON.stringify(previewLayout, null, 2)], { type: 'application/json' });
                const jsonLink = document.createElement('a');
                jsonLink.href = URL.createObjectURL(jsonBlob);
                jsonLink.download = 'preview_layout.json';
                jsonLink.click();
                URL.revokeObjectURL(jsonLink.href);

                // 保存纯净预览HTML
                const htmlBlob = new Blob([cleanPreviewHtml], { type: 'text/html' });
                const htmlLink = document.createElement('a');
                htmlLink.href = URL.createObjectURL(htmlBlob);
                htmlLink.download = 'clean_preview.html';
                htmlLink.click();
                URL.revokeObjectURL(htmlLink.href);

                alert('已保存预览窗格内容：preview_layout.json 和 clean_preview.html！');
            });

            function generatePreviewHtml(layout) {
                let elementsHtml = '';

                layout.forEach(item => {
                    if (item.type === 'text') {
                        elementsHtml += `
                        <div style="position: absolute; ${item.transform}; color: ${item.color}; font-size: ${item.fontSize}px; font-weight: bold; padding: 5px; border: 1px dashed rgba(255,255,255,0.3); user-select: none;">
                            ${item.content}
                        </div>`;
                    } else {
                        elementsHtml += `
                        <div style="position: absolute; ${item.transform}; width: ${item.width}; border: 2px dashed transparent;">
                            <img src="${item.src}" style="width: 100%; height: auto;" alt="Layout Image">
                        </div>`;
                    }
                });

                return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Layout Preview</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #000;
            overflow: hidden;
            font-family: sans-serif;
        }
        .container {
            position: relative;
            width: 100vw;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .canvas-wrapper {
            position: relative;
            width: 100%;
            max-width: calc((100vh - 40px) * 16 / 9);
            aspect-ratio: 16 / 9;
            background-color: #000;
            overflow: hidden;
        }
        #background-video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            z-index: 1;
        }
        .ui-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 2;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="canvas-wrapper">
            <video id="background-video" autoplay muted loop playsinline>
                <source src="assets/背景动画.mp4" type="video/mp4">
                您的浏览器不支持视频播放
            </video>
            <div class="ui-overlay">
                ${elementsHtml}
            </div>
        </div>
    </div>
</body>
</html>`;
            }

            // 生成纯净预览HTML（无编辑功能，直接基于预览窗格）
            function generateCleanPreviewHtml(layout) {
                let elementsHtml = '';

                layout.forEach(item => {
                    if (item.type === 'text') {
                        elementsHtml += `
                        <div style="position: absolute; left: ${item.x}px; top: ${item.y}px; color: ${item.color}; font-size: ${item.fontSize}px; font-weight: ${item.fontWeight}; user-select: none; pointer-events: none;">
                            ${item.content}
                        </div>`;
                    } else {
                        elementsHtml += `
                        <div style="position: absolute; left: ${item.x}px; top: ${item.y}px; width: ${item.width}px; height: ${item.height}px;">
                            <img src="${item.src}" style="width: 100%; height: 100%; object-fit: contain;" alt="UI Element">
                        </div>`;
                    }
                });

                return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clean Preview</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            background-color: #000;
            overflow: hidden;
            font-family: sans-serif;
        }
        .container {
            position: relative;
            width: 100vw;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .canvas-wrapper {
            position: relative;
            width: 100%;
            max-width: calc((100vh - 40px) * 16 / 9);
            aspect-ratio: 16 / 9;
            background-color: #000;
            overflow: hidden;
        }
        #background-video {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
            z-index: 1;
        }
        .ui-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 2;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="canvas-wrapper">
            <video id="background-video" autoplay muted loop playsinline>
                <source src="assets/背景动画.mp4" type="video/mp4">
                您的浏览器不支持视频播放
            </video>
            <div class="ui-overlay">
                ${elementsHtml}
            </div>
        </div>
    </div>
</body>
</html>`;
            }

            loadBtn.addEventListener('click', () => {
                const input = document.createElement('input');
                input.type = 'file';
                input.accept = 'application/json';
                input.onchange = e => {
                    const file = e.target.files[0];
                    if (!file) return;
                    const reader = new FileReader();
                    reader.onload = event => {
                        const layout = JSON.parse(event.target.result);
                        canvas.innerHTML = ''; // Clear canvas
                        elementCounter = 0;
                        layout.forEach(item => {
                            if (item.type === 'text') {
                                // Create text element
                                const textElement = document.createElement('div');
                                textElement.className = 'text-element';
                                textElement.id = item.id || 'text-' + (elementCounter++);
                                textElement.textContent = item.content;
                                textElement.style.position = 'absolute';
                                textElement.style.color = item.color || 'white';
                                textElement.style.fontSize = (item.fontSize || 24) + 'px';
                                textElement.style.fontWeight = 'bold';
                                textElement.style.cursor = 'move';
                                textElement.style.userSelect = 'none';
                                textElement.style.padding = '5px';
                                textElement.style.border = '1px dashed rgba(255,255,255,0.3)';
                                textElement.style.transform = item.transform;
                                textElement.dataset.type = 'text';
                                textElement.dataset.content = item.content;
                                textElement.dataset.fontSize = item.fontSize || '24';
                                textElement.dataset.color = item.color || 'white';
                                textElement.dataset.x = item.x;
                                textElement.dataset.y = item.y;

                                // Add double-click to edit
                                textElement.addEventListener('dblclick', () => {
                                    const newContent = prompt('编辑文字:', textElement.textContent);
                                    if (newContent !== null) {
                                        textElement.textContent = newContent;
                                        textElement.dataset.content = newContent;
                                    }
                                });

                                canvas.appendChild(textElement);
                                makeInteractive(textElement);
                            } else {
                                // Create image element (existing functionality)
                                const newElement = document.createElement('div');
                                newElement.classList.add('draggable');
                                newElement.id = item.id || 'element-' + (elementCounter++);
                                if (elementCounter <= parseInt(newElement.id.split('-')[1])) {
                                    elementCounter = parseInt(newElement.id.split('-')[1]) + 1;
                                }

                                const newImg = document.createElement('img');
                                newImg.src = item.src;
                                newImg.style.width = '100%';
                                newImg.style.height = 'auto';
                                newElement.appendChild(newImg);

                                const deleteBtn = document.createElement('div');
                                deleteBtn.className = 'delete-btn';
                                deleteBtn.innerHTML = '&times;';
                                deleteBtn.onclick = () => newElement.remove();
                                newElement.appendChild(deleteBtn);

                                newElement.style.width = item.width;
                                newElement.style.transform = item.transform;
                                newElement.setAttribute('data-x', item.x);
                                newElement.setAttribute('data-y', item.y);
                                newElement.setAttribute('data-src', item.src);

                                canvas.appendChild(newElement);
                                makeInteractive(newElement);
                            }
                        });
                    };
                    reader.readAsText(file);
                };
                input.click();
            });
        });
    </script>

</body>

</html>